const app = getApp()
var t = require("../../api.js");
var h = require("../../api.js"),
  a = getApp();
Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    cart_list: [],
    currentTab: 0,
    hideModal: true, //模态框的状态  true-隐藏  false-显示
    animationData: {},
    navScrollLeft: 0,
    cart_id: 0,
    page: 0,
    comment_page: 0,
    getPostsEnd: 0,
    cart_add_list: [],
    cart_list: [],
    posts_list: [],
    goods_one: 1,
    comment_N: 0,
    comment_list: [],
    comment_info: {
      reply_id: 0,
      comment: "",
      posts_id: 0
    },
    button_alert: false,
    placeholder_data: '评论',
    comment_posts_id: 0,
    add_posts: true,
    indicatorDots: false,
    autoplays: true,
    interval: 4000,
    circular: true,
    duration: 800,
    swiperCurrent: 0,
    shop_info: [],
    banner_list: [],
    data: {},
    height:"82rpx",
    open_:false,
    open2:false,
    tianqi:'',
    isIphoneX:false,
    state: -1,
  },
  //事件处理函数
  onLoad: function() {
    var that = this;
    wx.getStorage({
      key: 'good_posts',
      success(res) {

      },
    })
    app.pageOnLoad(this, t);
    that.getPosts();
    this.getTianQi();
    this.themeColor()
  },
  themeColor: function () {
    var cl = wx.getStorageSync('_navigation_bar_color').themeColor;
    var cl_b = !cl || cl == '#ffffff' ? '#ff4544' : cl;
    var color_rgb = this.hexToRgb(cl_b);
    var back_g = 'rgba(' + color_rgb.r + ',' + color_rgb.g + ',' + color_rgb.b + ',.5)'
    this.setData({
      all_color: cl ? cl : '#ffffff',
      back_g: back_g
      // back_end: back_end
    });
  },
  hexToRgb: function (hex) {
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? {
      r: parseInt(result[1], 16),
      g: parseInt(result[2], 16),
      b: parseInt(result[3], 16)
    } : null;
  },
  getPosts: function() {
    var that = this;
    if (that.data.getPostsEnd && that.data.page > 0) {
      wx.showToast({
        icon: 'none',
        title: '没有更多帖子'
      })
      return false;
    }
    wx.showLoading({
      title: '玩命加载中',
    })
    var shop_info = wx.getStorageSync('address_info')
    a.request({
      url: t.posts.list,
      method: "POST",
      data: {
        cart_id: that.data.cart_id,
        page: that.data.page,
        shop_id:shop_info.shop_id
      },
      success: function(t) {
        wx.hideLoading()
        if (t.code == 0) {
          if (t.data.posts_list.length < 15) {
            that.setData({
              getPostsEnd: 1,
            })
          }
          t.data.posts_list = that.xuanran_good(t.data.posts_list);
          that.setData({
            cart_add_list: t.data.cart_add_list,
            cart_list: t.data.cart_list,
            banner_list: t.data.banner_list,
            shop_info: t.data.shop_info,
            page: that.data.page + 1,
            bg_image: t.data.bg_image
          })
        }
      },
      complete: function() {
        wx.stopPullDownRefresh();
      }
    })
  },
  xuanran_good: function(tt) {
    var that = this;
    wx.getStorage({
      key: 'good_posts',
      success(res) {
        for (var i = 0; i < tt.length; i++) {
          if (res.data.indexOf(tt[i].id) > -1) {
            tt[i].good = 1
          } else {
            tt[i].good = 0
          }
          tt[i].content = unescape(tt[i].content);
          tt[i].title = unescape(tt[i].title)
        }
        tt = that.data.posts_list.concat(tt)
        that.setData({
          posts_list: tt
        })
      },
      fail() {
        for (var i = 0; i < tt.length; i++) {
          tt[i].good = 0;
          tt[i].content = unescape(tt[i].content);
          tt[i].title = unescape(tt[i].title)
        }
        tt = that.data.posts_list.concat(tt)
        that.setData({
          posts_list: tt
        })
      }
    })
  },

  onShow: function() {
    //wx.hideTabBar()
    getApp().pageOnShow(this);
    
    if (this.data.cart_add_list == [] || this.data.cart_list == [] || this.data.posts_list == []){
      this.getPosts();
    }
    this.show_navs();
    this.cart_num();
  },
  //获取天气信息
  getTianQi:function () {
    var that = this;
    wx.getLocation({
      success: function (t) {
        a.request({
          url: h.default.get_location,
          method: "GET",
          data: {
            longitude: t.longitude,
            latitude: t.latitude
          },
          success: function (t) {
            console.log(t);
            a.request({
              url: h.posts.tian_qi,
              method: "GET",
              data: {
                city: t.city
              },
              success: function (t) {
                console.log(t);
                  if(t.status == 1000){
                      if (t.data.yesterday.image_url){
                        var tianqi = t.data.yesterday.low.split("低温").join("") + '~' + t.data.yesterday.high.split("高温").join("")
                      }else{
                        var tianqi = t.data.yesterday.type + t.data.yesterday.low.split("低温").join("") + '~' + t.data.yesterday.high.split("高温").join("")
                      }

                      that.setData({
                        tianqi:tianqi,
                        tianqi_image : t.data.yesterday.image_url
                      })
                  }
              },
              fail: function (t) {
                
              },
            });
          },
          fail: function (t) {
            o.setData({
              myAddress: "定位失败",
            })
          },
        });
      },
      complete: function () {
       
      }
    });


    
  },

  goodsQrcodeClick: function(t) {
    var a = t.currentTarget.dataset.src;
    var pid = t.currentTarget.dataset.pid;
    var image_arr = this.data.posts_list[pid].images;
    var urls = [];
    for (var value of image_arr){
      urls.push(value.feil_url)
    }
    wx.previewImage({
      current:a,
      urls: urls
    });
  },
  goods_show: function(tt) {
    var a = tt.currentTarget.dataset.index;
    var that = this;
    that.data.posts_list[a].goods_one = that.data.posts_list[a].goods_one ? 0 : 1;
    this.setData({
      posts_list: that.data.posts_list
    })
  },
  onReachBottom: function(t) {
    this.getPosts()
  },
  good_Y: function(tt) {
    var posts_id = tt.currentTarget.dataset.id;
    var index = tt.currentTarget.dataset.index;
    var that = this;
    a.request({
      url: t.posts.good,
      method: "POST",
      data: {
        id: posts_id
      },
      success: function(t) {
        var posts_list = that.data.posts_list;
        posts_list[index].good = 1;
        posts_list[index].good_num++;
        that.setData({
          posts_list: posts_list
        })
        wx.getStorage({
          key: 'good_posts',
          success(res) {
            res.data.push(posts_id);
            wx.setStorage({
              key: 'good_posts',
              data: res.data
            })
          },
          fail() {
            var arr = []
            arr.push(posts_id)
            wx.setStorage({
              key: 'good_posts',
              data: arr
            })
          }
        })
      }
    })
  },

  switchNav(event) {

    var that = this;
    that.setData({
      cart_id: event.currentTarget.dataset.id,
      page: 0,
      posts_list: [],
      getPostsEnd:0
    })
    that.getPosts();
    var cur = event.currentTarget.dataset.current;
    //每个tab选项宽度占1/5
    var singleNavWidth = this.data.windowWidth / 5;
    //tab选项居中                            
    this.setData({
      navScrollLeft: (cur - 2) * singleNavWidth
    })
    if (this.data.currentTab == cur) {
      return false;
    } else {
      this.setData({
        currentTab: cur
      })
    }
  }, // 显示遮罩层
  showModal: function(tt) {
    var a = tt.currentTarget.dataset.id ? tt.currentTarget.dataset.id : this.data.comment_posts_id;
    this.get_comment(a);
    var that = this;
    that.setData({
      hideModal: false,
      comment_info: {
        reply_id: 0,
        comment: "",
        posts_id: a,
        index: tt.currentTarget.dataset.index
      },
    })
    var animation = wx.createAnimation({
      duration: 200, //动画的持续时间 默认400ms   数值越大，动画越慢   数值越小，动画越快
      timingFunction: 'linear', //动画的效果 默认值是linear
    })
    this.animation = animation
    that.fadeIn(); //调用显示动画
  },

  // 获取评论
  get_comment: function(tt) {
    if (tt != this.data.comment_posts_id) {
      this.setData({
        comment_N: 0,
        comment_list: [],
        comment_posts_id: tt,
        comment_page: 0,
        placeholder_data:'评论'
      })
    }
    if (this.data.comment_N == 1) {
      // wx.showToast({
      //   icon: 'none',
      //   title: '没有更多评论'
      // })
      return false;
    }
    wx.showLoading({
      title: '玩命加载中',
    })
    var that = this;
    a.request({
      url: t.posts.get_comment,
      method: "POST",
      data: {
        id: tt,
        page: that.data.comment_page
      },
      success: function(t) {
        wx.hideLoading()
        if (t.code == 0) {
          var commment_n = 0;
          if (t.data.comment_list.length < 15) {
            var commment_n = 1;
          }
          for (var i in t.data.comment_list) {
            t.data.comment_list[i].comment = unescape(t.data.comment_list[i].comment)
          }
          tt = that.data.comment_list.concat(t.data.comment_list)
          
          that.setData({
            comment_N: commment_n,
            comment_list: tt,
            comment_page: that.data.comment_page + 1
          })

        }
      }
    })
  },

  // 隐藏遮罩层
  hideModal: function() {
    var that = this;
    var animation = wx.createAnimation({
      duration: 200, //动画的持续时间 默认400ms   数值越大，动画越慢   数值越小，动画越快
      timingFunction: 'linear', //动画的效果 默认值是linear
    })
    this.animation = animation
    that.fadeDown(); //调用隐藏动画   
    setTimeout(function() {
      that.setData({
        hideModal: true
      })
    }, 200) //先执行下滑动画，再隐藏模块

  },

  //动画集
  fadeIn: function() {
    this.animation.translateY(0).step()
    this.setData({
      animationData: this.animation.export() //动画实例的export方法导出动画数据传递给组件的animation属性
    })
  },
  fadeDown: function() {
    this.animation.translateY(300).step()
    this.setData({
      animationData: this.animation.export(),
    })
  },
  show_navs: function() {
    var that = this;
    var nav = wx.getStorageSync("_navbar");
    var url = "/pages/posts/index";
    if (typeof that.getTabBar === 'function' &&
        that.getTabBar()) {
        that.getTabBar().setData({
          selected: -1,
          is_show: 1
        })
    }


    for (var i = 0; i < nav.navs.length; i++) {
      if (nav.navs[i].url == url) {
        if (getApp().globalData.nav_index == i) {
          if (typeof that.getTabBar === 'function' &&
            that.getTabBar()) {
            that.getTabBar().setData({
              selected: getApp().globalData.nav_index,
              is_show: 1
            })
          }
        } else {
          getApp().globalData.nav_index = i;
          if (typeof that.getTabBar === 'function' &&
            that.getTabBar()) {
            that.getTabBar().setData({
              selected: getApp().globalData.nav_index,
              is_show: 1
            })
          }
        }
      }
    }
  },

  bindContentInput: function(t) {
    this.data.comment_info.comment = t.detail.value, this.setData({
      comment_info: this.data.comment_info
    });
  },
  laert_jianpan: function(tt) {
    var that = this;
    var id = tt.currentTarget.dataset.id;
    var name = tt.currentTarget.dataset.name;
    if (name && id) {
      that.data.comment_info.reply_id = id;
      that.setData({
        button_alert: true,
        placeholder_data: '回复 ' + name,
        comment_info: that.data.comment_info
      })
    } else {
      that.setData({
        button_alert: true,
      })
    }
  },
  add_comment: function(tt) {
    var user_info = wx.getStorageSync("user_info");
    if (!(user_info && user_info.id > 0)) {
      this.setData({
        user_info_show: !0
      })
      return false;
    }
    var comment_info = this.data.comment_info;
    if (comment_info.comment == '') {
      wx.showToast({
        icon: 'none',
        title: '请输入评论内容'
      })
      return false;
    }
    wx.showLoading({
      title: '提交中',
    })
    var that = this;
    a.request({
      url: t.posts.add_comment,
      method: "POST",
      data: {
        comment: comment_info.comment,
        posts_id: comment_info.posts_id,
        reply_id: comment_info.reply_id
      },
      success: function(t) {
        wx.hideLoading()
        if (t.code == 0) {
          t.data = [t.data].concat(that.data.comment_list)
          for (var i in t.data) {
            t.data[i].comment = unescape(t.data[i].comment)
          }
          that.data.comment_info.comment = '';
          that.data.posts_list[that.data.comment_info.index].comment_num++;
          that.setData({
            button_alert: false,
            comment_list: t.data,
            comment_info: that.data.comment_info,
            posts_list: that.data.posts_list
          })
        }else {
          wx.showToast({
            icon: 'none',
            title: t.msg
          })
        }
      }
    })
  },
  // 发帖分类
  add_posts: function() {
    var that = this;
    a.request({
      url: t.default.login_style,
      method: "POST",
      success: function (t) {
        if (t == 0) {
          that.setData({
            user_info_show: !0
          })
        }else {
          that.setData({
            add_posts: !that.data.add_posts
          })
        }
      },

    })
  },
  onPullDownRefresh: function() {
    this.setData({
      cart_id: 0,
      page: 0,
      comment_page: 0,
      getPostsEnd: 0,
      cart_add_list: [],
      cart_list: [],
      posts_list: [],
      goods_one: 1,
      comment_N: 0,
      comment_list: [],
      currentTab: 0
    })
    this.getPosts();
  },
  // 获取购物车数量
  cart_num: function () {
    var that = this;
    wx.getStorage({
      key: 'user_info',
      success: function (res) {
        a.request({
          url: h.cart.list,
          success: function (t) {
            if (0 == t.code) {
              if (typeof that.getTabBar === 'function' &&
                that.getTabBar()) {
                if (t.data.mch_list.length > 0) {
                  var length = t.data.list.length + t.data.mch_list[0].list.length;
                } else {
                  var length = t.data.list.length
                }
                that.getTabBar().setData({
                  cart_num: length
                })
              }
            }
          }
        });
      },
    })
  },
  toggle: function (e) {
    var that = this;
    var index = 0;
    var id = e.currentTarget.dataset.id;
    var list_state = that.data.state;
    if (list_state == id) {
      that.setData({
        state: 0
      })
    } else {
      that.setData({
        state: id
      })
    }
  },

})